package com.qiantu.phone.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

public class CustomSeekCurtain extends View {

    public int clickThreshold;//点击阈值
    public int moveThreshold;//滑动阈值

    private float mTouchDownX;
    private float mTouchDownY;
    private Drawable curtainLeftDrawable;
    private boolean curtainLeftDrawableIsAllRound;
    private Drawable curtainRightDrawable;
    private Drawable curtainTrackBg;
    private float curtainTrackHeight;
    // 画笔
    private Paint mPaint;
    private float progress;
    private float preProgress;
    private int progressPercentage;
    private Rect mLeftRect;
    private Rect mRightRect;
    private float canSlideTotalWidth;
    private int gapWidth;
    private OnSeekBarChangeListener mOnSeekBarChangeListener;
    private boolean isLeft;
    private boolean isOverTouchSlop;
    private boolean hasDrag;
    private int dragWidth;
    private int paddingLeftRight;
    private long lastDownTime;
    private float slidDistance;
    private boolean isFirst;
    private boolean isOpen;
    private boolean isOnline = true;
    //关闭状态是否能操作
    private boolean offCanDrag = true;
    //有没有move
    private boolean hasMove;
    private int drawableRadius;

    public CustomSeekCurtain(Context context) {
        this(context, null);
    }

    public CustomSeekCurtain(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomSeekCurtain(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = attrs == null ? null : getContext().obtainStyledAttributes(attrs, R.styleable.CustomSeekCurtain);
        if (ta != null) {
            curtainLeftDrawable = ta.getDrawable(R.styleable.CustomSeekCurtain_curtain_left_drawable);
            curtainLeftDrawableIsAllRound = ta.getBoolean(R.styleable.CustomSeekCurtain_curtain_left_drawable_is_all_round, false);
            curtainRightDrawable = ta.getDrawable(R.styleable.CustomSeekCurtain_curtain_right_drawable);
            curtainTrackBg = ta.getDrawable(R.styleable.CustomSeekCurtain_curtain_track_bg);
            curtainTrackHeight = ta.getDimension(R.styleable.CustomSeekCurtain_curtain_track_height, dp2px(20));
            paddingLeftRight = (int) ta.getDimension(R.styleable.CustomSeekCurtain_curtain_left_right_padding, dp2px(4));
            hasDrag = ta.getBoolean(R.styleable.CustomSeekCurtain_curtain_has_drag, false);
            ta.recycle();
        }
//        moveThreshold = ViewConfiguration.get(context).getScaledTouchSlop();
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setShadowLayer(3, 0, 3, 0x99000000);

//        gapWidth = dp2px(0.5f);
//        gapWidth = gapWidth == 0 ? 1 : gapWidth;
        mLeftRect = new Rect();
        mRightRect = new Rect();

        if (hasDrag) {
            dragWidth = dp2px(12) + paddingLeftRight;
        } else {
            dragWidth = 0;
        }
//        // 设置滑动监听
//        this.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                // NO OP
//
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//                if (mIndicatorSeekBarChangeListener != null) {
//                    mIndicatorSeekBarChangeListener.onStartTrackingTouch(seekBar);
//                }
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//                if (mIndicatorSeekBarChangeListener != null) {
//                    mIndicatorSeekBarChangeListener.onStopTrackingTouch(seekBar);
//                }
//            }
//        });
        clickThreshold = dp2px(2);
        moveThreshold = dp2px(3);
        drawableRadius = dp2px(4);
    }

    public void setCurtainLeftDrawable(Drawable curtainLeftDrawable) {
        this.curtainLeftDrawable = curtainLeftDrawable;
    }

    public void setCurtainRightDrawable(Drawable curtainRightDrawable) {
        this.curtainRightDrawable = curtainRightDrawable;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mTouchDownX = event.getX();
                mTouchDownY = event.getY();
                lastDownTime = System.currentTimeMillis();
                isFirst = true;
                if (curtainRightDrawable == null) {
                    isLeft = true;
//                    //判断固定范围之内可以拖动 固定范围之外只能点击
//                    isOnlyClick = !(mTouchDownX >= mLeftRect.right - dragWidth - paddingLeftRight && mTouchDownX <= mLeftRect.right + paddingLeftRight);
                } else {
                    int centerX = (int) (getWidth() / 2f + 0.5f);
                    isLeft = mTouchDownX < centerX;
                    Log.i("lzzzx", "mTouchDownX:" + mTouchDownX);
                    Log.i("lzzzx", "isLeft:" + isLeft);
//                    int rightEdge =mLeftRect.right + paddingLeftRight;
//                    rightEdge = rightEdge > centerX ? centerX : rightEdge;
//                    int leftEdge = mRightRect.left - paddingLeftRight;
//                    leftEdge = leftEdge < centerX ? centerX : leftEdge;
//                    //判断固定范围之内可以拖动 固定范围之外只能点击
//                    isOnlyClick = !((mTouchDownX >= mLeftRect.right - dragWidth - paddingLeftRight && mTouchDownX <= rightEdge)
//                            || (mTouchDownX >= leftEdge && mTouchDownX <= mRightRect.left + dragWidth + paddingLeftRight));
                }
                //已滑动距离
                slidDistance = progress * canSlideTotalWidth;
                //重置, 触摸中不进行ScaledTouchSlop判断
                isOverTouchSlop = false;
                break;
            case MotionEvent.ACTION_MOVE:
                float x = event.getX();
                float distance = 0;
                if (!isLeft) {
                    distance = mTouchDownX - x;
                } else {
                    distance = x - mTouchDownX;
                }
                if ((Math.abs(x - mTouchDownX) >= moveThreshold || hasMove)//第一次滑动距离达到一定一定距离
                        && System.currentTimeMillis() - lastDownTime > 150
//                        && (Math.abs(distance) >= mScaledTouchSlop || isOverTouchSlop)
                ) {
                    getParent().requestDisallowInterceptTouchEvent(true);
                    //关闭状态不可操作
                    if (!offCanDrag && !isOpen) {
                        hasMove = false;
                        return false;
                    }
                    if (isFirst) {
                        isFirst = false;
                        setAlpha(0.8f);
                        if (mOnSeekBarChangeListener != null) {
                            mOnSeekBarChangeListener.onStartTrackingTouch();
                        }
                    }
                    isOverTouchSlop = true;

                    distance = distance + slidDistance;
                    distance = distance > canSlideTotalWidth ? canSlideTotalWidth : distance;
                    progress = distance / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    Log.i("luzx", "progress" + progress);
                    //关闭状态可拖动才根据百分比0重置开关
                    if (offCanDrag) {
                        if (progress > 0) {
                            isOpen = true;
                        } else {
                            isOpen = false;
                        }
                    }
                    hasMove = true;
                    calculateProgressPercentage();
                    invalidate();
                    if (mOnSeekBarChangeListener != null) {
                        mOnSeekBarChangeListener.onProgressChanged(progressPercentage);
                    }
                } else {
                    hasMove = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                float upX = event.getX();
                float upY = event.getY();
                float clickDistance = (float) Math.sqrt(Math.pow(Math.abs(upX - mTouchDownX), 2) + Math.pow(Math.abs(upY - mTouchDownY), 2));
                if (
//                        isOnlyClick &&
                        clickDistance <= clickThreshold) {
                    //关闭状态不可操作，返回原有进度
                    if (!offCanDrag && !isOpen) {
                        if (mOnSeekBarChangeListener != null) {
                            calculateProgressPercentage();
                            playSoundEffect(SoundEffectConstants.CLICK);
                            mOnSeekBarChangeListener.onStopTrackingTouch(progressPercentage);
                        }
                        return false;
                    }
                    getParent().requestDisallowInterceptTouchEvent(false);
                    if (!isLeft) {
                        upX = getWidth() - upX;
                    }
                    upX = upX - dragWidth;
                    upX = upX < 0 ? 0 : upX;
                    upX = upX > canSlideTotalWidth ? canSlideTotalWidth : upX;
                    progress = upX / canSlideTotalWidth;
                    progress = progress < 0 ? 0 : progress;
                    progress = progress >= 0.995 ? 1 : progress;
                    Log.i("luzx", "progress" + progress);
                    //关闭状态可拖动才根据百分比0重置开关
                    if (offCanDrag) {
                        if (progress > 0) {
                            isOpen = true;
                        } else {
                            isOpen = false;
                        }
                    }
                    calculateProgressPercentage();
                    invalidate();
                    if (mOnSeekBarChangeListener != null) {
                        playSoundEffect(SoundEffectConstants.CLICK);
                        mOnSeekBarChangeListener.onStopTrackingTouch(progressPercentage);
                    }
                } else {
                    if (mOnSeekBarChangeListener != null && hasMove) {
                        playSoundEffect(SoundEffectConstants.CLICK);
                        mOnSeekBarChangeListener.onStopTrackingTouch(progressPercentage);
                    }
                }
                setAlpha(1f);
//                isOnlyClick = false;
                isFirst = false;
                hasMove = false;
                break;
            case MotionEvent.ACTION_CANCEL:
                setAlpha(1f);
//                isOnlyClick = false;
                isFirst = false;
                hasMove = false;
                break;
        }
        return true;
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        curtainTrackBg.draw(canvas);
        //离线
        if (!isOnline) {
            return;
        }
        if (progressPercentage == 0) {
//            curtainLeftDrawable.setAlpha(0);
            if (curtainLeftDrawable instanceof LayerDrawable) {
                LayerDrawable layerDrawable = (LayerDrawable) curtainLeftDrawable;
                Drawable drawable = layerDrawable.getDrawable(0);
                drawable.setAlpha(0);
            }
            if (curtainRightDrawable != null) {
//                curtainRightDrawable.setAlpha(0);
                if (curtainRightDrawable instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) curtainRightDrawable;
                    Drawable drawable = layerDrawable.getDrawable(0);
                    drawable.setAlpha(0);
                }
            }
        } else if (progressPercentage == 100) {
            //右边是null,左边到达100的时候设置圆角
            if (curtainRightDrawable == null) {
                if (curtainLeftDrawable instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) curtainLeftDrawable;
                    GradientDrawable drawable = (GradientDrawable) layerDrawable.getDrawable(0);
                    drawable.setAlpha(255);
                    drawable.setCornerRadius(drawableRadius);
                    if (isOpen) {
                        drawable.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                    } else {
//                        drawable.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                        drawable.setAlpha(51);
                    }
                }
            } else {
                //设置透明度和圆角
                if (curtainLeftDrawable instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) curtainLeftDrawable;
                    GradientDrawable drawable = (GradientDrawable) layerDrawable.getDrawable(0);
                    drawable.setAlpha(255);
                    if (isOpen) {
                        drawable.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                    } else {
//                        drawable.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                        drawable.setAlpha(51);
                    }
                    if (drawable instanceof GradientDrawable) {
                        ((GradientDrawable) drawable).setCornerRadii(new float[]{
                                drawableRadius,//radiusTopLeftx
                                drawableRadius,//radiusTopLefty
                                0,//radiusTopRightx
                                0,//radiusTopRighty
                                0,//radiusBottomRightx
                                0,//radiusBottomRighty
                                drawableRadius,//radiusBottomLeftx
                                drawableRadius//radiusBottomLefty
                        });
                    }
                }
                if (curtainRightDrawable instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) curtainRightDrawable;
                    GradientDrawable drawable = (GradientDrawable) layerDrawable.getDrawable(0);
                    drawable.setAlpha(255);
                    if (isOpen) {
                        drawable.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                    } else {
//                        drawable.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                        drawable.setAlpha(51);
                    }
                }
            }
        } else {
            if (curtainLeftDrawable instanceof LayerDrawable) {
                LayerDrawable layerDrawable = (LayerDrawable) curtainLeftDrawable;
                GradientDrawable leftFirstDrawable = (GradientDrawable) layerDrawable.getDrawable(0);
                leftFirstDrawable.setAlpha(255);
                if (isOpen) {
                    leftFirstDrawable.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                } else {
//                    leftFirstDrawable.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                    leftFirstDrawable.setAlpha(51);
                }
                //左边的Drawable不是全圆角，就设置圆角
                if(!curtainLeftDrawableIsAllRound){
                    if (curtainRightDrawable == null) {
                        float diff = getWidth() - progress * getWidth();
                        float radius = 0;
                        if (diff <= drawableRadius) {
                            radius = drawableRadius - diff;
                        } else {
                            radius = 0;
                        }
                        leftFirstDrawable.setCornerRadii(new float[]{
                                drawableRadius,//radiusTopLeftx
                                drawableRadius,//radiusTopLefty
                                radius,//radiusTopRightx
                                radius,//radiusTopRighty
                                radius,//radiusBottomRightx
                                radius,//radiusBottomRighty
                                drawableRadius,//radiusBottomLeftx
                                drawableRadius//radiusBottomLefty
                        });
                    } else {
                        leftFirstDrawable.setCornerRadii(new float[]{
                                drawableRadius,//radiusTopLeftx
                                drawableRadius,//radiusTopLefty
                                0,//radiusTopRightx
                                0,//radiusTopRighty
                                0,//radiusBottomRightx
                                0,//radiusBottomRighty
                                drawableRadius,//radiusBottomLeftx
                                drawableRadius//radiusBottomLefty
                        });
                    }
                }
            }
            if (curtainRightDrawable != null) {
                if (curtainRightDrawable instanceof LayerDrawable) {
                    LayerDrawable layerDrawable = (LayerDrawable) curtainRightDrawable;
                    GradientDrawable drawable = (GradientDrawable) layerDrawable.getDrawable(0);
                    drawable.setAlpha(255);
                    if (isOpen) {
                        drawable.setColor(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
                    } else {
//                        drawable.setColor(getResources().getColor(AppApplication.getInstance().getThemeColor(R.attr.secondaryColor4)));
                        drawable.setAlpha(51);
                    }
                }
            }
        }
        if (curtainRightDrawable != null) {
            mRightRect.left = (int) ((getWidth() + gapWidth) / 2 + +((1 - progress) * canSlideTotalWidth));
            curtainRightDrawable.setBounds(mRightRect);
            curtainRightDrawable.draw(canvas);
        }
        mLeftRect.right = (int) (progress * canSlideTotalWidth + 0.5f + dragWidth);
//        Log.i("lzx", "left:" + mRightRect.left);
//        Log.i("lzx", "right:" + mRightRect.right);
        curtainLeftDrawable.setBounds(mLeftRect);
        curtainLeftDrawable.draw(canvas);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int dw = getMeasuredWidth();
        int dh = (int) curtainTrackHeight;
        dh += getPaddingTop() + getPaddingBottom();
        mLeftRect.left = paddingLeftRight;
        mLeftRect.top = 0;
        mLeftRect.bottom = dh;
        if (curtainRightDrawable != null) {
            mLeftRect.right = (dw / 2) - (gapWidth / 2);
            mRightRect.left = mLeftRect.right + gapWidth;
            mRightRect.right = dw - paddingLeftRight;
            mRightRect.top = 0;
            mRightRect.bottom = dh;
            curtainRightDrawable.setBounds(mRightRect);
        } else {
            mLeftRect.right = dw - paddingLeftRight;
        }
        curtainLeftDrawable.setBounds(mLeftRect);
        canSlideTotalWidth = mLeftRect.right - dragWidth;
        curtainTrackBg.setBounds(paddingLeftRight, 0, dw - paddingLeftRight, dh);
        setMeasuredDimension(dw, dh);
    }

    public float getProgress() {
        return progress;
    }

    public int getProgressPercentage() {
        return progressPercentage;
    }

    public void setProgress(float progress) {
        if (this.progress * 100 == progress) {
            return;
        }
        this.progress = progress / 100f;
        calculateProgressPercentage();
        invalidate();
    }

    private void calculateProgressPercentage() {
        progressPercentage = (int) (progress * 100 + 0.5f);
    }

    public void setOpen(boolean open) {
        if (isOpen == open) {
            return;
        }
        isOpen = open;
        invalidate();
    }

    public void isOnline(boolean isOnline) {
        if (this.isOnline == isOnline) {
            return;
        }
        this.isOnline = isOnline;
        if (isOnline) {
            setEnabled(true);
        } else {
            setEnabled(false);
        }
        invalidate();
    }

    public void setOffCanDrag(boolean offCanDrag) {
        this.offCanDrag = offCanDrag;
    }

    /**
     * 进度监听
     */
    public interface OnSeekBarChangeListener {
        /**
         * 进度监听回调
         * =
         *
         * @param progress 进度
         */
        public void onProgressChanged(int progress);

        /**
         * 开始拖动
         */
        public void onStartTrackingTouch();

        /**
         * 停止拖动
         */
        public void onStopTrackingTouch(int progress);
    }

    public void setOnSeekBarChangeListener(OnSeekBarChangeListener changeListener) {
        this.mOnSeekBarChangeListener = changeListener;
    }

    /**
     * dp转px
     *
     * @param dp dp值
     * @return px值
     */
    public int dp2px(float dp) {
        return (int) (getResources().getDimensionPixelSize(R.dimen.dp_1) * dp);
    }
}
